﻿CREATE proc [dbo].[proc_Customer_Track_Create]
(
	@CustomerId uniqueidentifier,
	@IntentionsId int,
	@PublicityDemandId int,
	@NetworkConsciousnessId int,
	@GenjinId int,
	@Record text,
	@UpName nvarchar(50),
	@RemindDate datetime
)
As
Begin
	Declare @TempProtectName nvarchar(50),@ProtectId int,@ProtectDate datetime,@tmpPId int

	Set @TempProtectName = Null	--初始化
	Select @TempProtectName=ProtectName,@ProtectId=ProtectId,@ProtectDate=ProtectDate From Customer Where CustomerId=@CustomerId
	If @TempProtectName Is Null	--已经被踢入公库了，不能再写保护
		Return

	If @ProtectId Is Null	--未知的错误
		Return

	If(@TempProtectName <> @UpName)	--领导级帮员工写备注时用
		Set @UpName = @TempProtectName

	Declare @CompanyId int,@DepartmentId int,@OrderCount int
	EXEC @CompanyId=proc_Company_GetID @UpName,@CompanyId
	EXEC @DepartmentId=proc_Department_GetID @Upname,@DepartmentId

	--直接放弃时无法获得这3项的值，所以在此处取 By ZHT 2014-10-23
	If @IntentionsId=-1 And @PublicityDemandId=-1 And @NetworkConsciousnessId=-1
		Select @IntentionsId=IsNull(IntentionsId,0),@PublicityDemandId=IsNull(PublicityDemandId,0),@NetworkConsciousnessId=IsNull(NetworkConsciousnessId,0)	From Customer Where CustomerId=@Customerid
	
	--插入批注记录
	Insert Into Customer_Track(Customerid,IntentionsId,PublicityDemandId,NetworkConsciousnessId,GenjinId,Record,UpName,UpTime,DepartmentId,CompanyId)
	Values(@Customerid,@IntentionsId,@PublicityDemandId,@NetworkConsciousnessId,@GenjinId,@Record,@UpName,GetDate(),@DepartmentId,@CompanyId)
	
	--插入下次预约时间及更新客户信息
	If @GenjinId=1 Or @GenjinId=6	--保护或跟踪
		Begin
			If @RemindDate>Convert(DateTime,'2012-11-26')	--选择了下次联系日期
				Insert Into Customer_Remind(CustomerId,RemindDate,UserName,UpTime)
				Values(@CustomerId,@RemindDate,@UpName,GetDate())

			If @ProtectId=1	--申领转保护/跟踪，置保护/跟踪日期
				Set @ProtectDate=GetDate()

			If @GenjinId=1
				Set @tmpPId = 2	--保护状态
			Else
				Set @tmpPId = 4	--跟踪状态

			Update Customer Set IntentionsId=@IntentionsId,PublicityDemandId=@PublicityDemandId,NetworkConsciousnessId=@NetworkConsciousnessId,TrackDate=GetDate(),
			ProtectName=@UpName,ProtectDate=@ProtectDate,ProtectId=@tmpPId Where CustomerId=@Customerid
		End
	Else	--踢入公库
		Begin
	--		If @ProtectId=1 Or @ProtectId=4	--跟踪或保护状态的客户，踢入公库后第二天即可参与申领
	--			Update Customer Set IntentionsId=@IntentionsId,PublicityDemandId=@PublicityDemandId,NetworkConsciousnessId=@NetworkConsciousnessId,TrackDate=GetDate(),
	--			ProtectName=NULL,ProtectDate=NULL,ProtectId=1 Where CustomerId=@Customerid
	--		Else	--否则10天后再参与
			Update Customer Set IntentionsId=@IntentionsId,PublicityDemandId=@PublicityDemandId,NetworkConsciousnessId=@NetworkConsciousnessId,TrackDate=GetDate(),
			ProtectName=NULL,ProtectDate=NULL,ProtectId=1,UpTime=GetDate() Where CustomerId=@Customerid

			Select @OrderCount=Count(0) From [Order] Where CusId=@Customerid
			If @OrderCount>0	--有成单记录，则由“公库”状态自动变为“已签单”状态，不再参与销售的申领
				Update Customer Set ProtectId=3,OrdersCount=@OrderCount Where CustomerId=@Customerid
		End
End